import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, logout, getUserInfo } from '@/api/user'
import type { User } from '@/types/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
 // const userInfo = ref<User | null>(null)
  const userInfo = ref(localStorage.getItem('userInfo') || '')
  const roles = ref<string[]>([])

  // 登录
  const loginAction = async (username: string, password: string) => {
    try {
      const res = await login(username, password)
      token.value = res.data.tokenValue
      localStorage.setItem('token', token.value)
      localStorage.setItem('userInfo',JSON.stringify(res.data.user))
      return res
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
     const res = await getUserInfo()

      console.log(res,'111')
      // 根据用户类型设置角色
      if (userInfo.value) {
        switch(userInfo.value.userType) {
          case 0:
            roles.value = ['admin']
            break
          case 1:
            roles.value = ['elderly']
            break
          case 2:
            roles.value = ['volunteer']
            break
          default:
            roles.value = ['guest']
        }
      }

      return res
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 登出
  const logoutAction = async () => {
    try {
      if (token.value) {
        await logout()
      }
      resetState()
      return true
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 重置状态
  const resetState = () => {
    token.value = ''
    userInfo.value = null
    roles.value = []
    localStorage.removeItem('token')
  }

  return {
    token,
    userInfo,
    roles,
    loginAction,
    getUserInfoAction,
    logoutAction,
    resetState
  }
})
